package com.ych.modules.common.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ych.modules.base.dbEntity.TUserAccountEntity;
import com.ych.modules.base.dbEntity.TUserCardEntity;
import com.ych.modules.base.dbEntity.TUserCashOrderEntity;
import com.ych.modules.base.service.ITUserAccountService;
import com.ych.modules.base.service.ITUserCardService;
import com.ych.modules.base.service.ITUserCashOrderService;
import com.ych.modules.common.entity.query.QueryUserCashOrderEntity;
import com.ych.modules.common.service.UserCashOrderService;
import com.ych.utils.TLMap;
import com.ych.utils.UUID;
import com.ych.utils.beanToMap.BeanMapUtil;
import com.ych.utils.mysqlPageUtil.Query;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2021/3/20
 * Time: 16:20
 * Description:
 */
@Service("UserCashOrderService")
public class UserCashOrderServiceImpl implements UserCashOrderService {
    @Autowired
    private       ITUserCashOrderService itUserCashOrderService;
    @Autowired
    private       ITUserAccountService   itUserAccountService;
    @Autowired
    private       ITUserCardService      itUserCardService;
    /**
     * 提现收取的服务费比例，5%
     */
    private final BigDecimal             chargeRate = new BigDecimal("0.05");

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void createCashOrder(TUserCashOrderEntity entity) {
        this.validateParam(entity);
        TUserAccountEntity accountEntity = itUserAccountService.selectById(TLMap.getUserId());
        if (accountEntity.getBrokerageAmount().compareTo(entity.getAmount()) == -1) {
            throw new RuntimeException("余额不足");
        }
        entity.setCashOrderId(UUID.randomUUID());
        entity.setUserId(TLMap.getUserId());
        TUserCardEntity cardEntity = itUserCardService.selectById(entity.getUserCardId());
        entity.setCardType(cardEntity.getCardType());
        switch (cardEntity.getCardType()) {
            case "10014001"://支付宝
                entity.setCashCardAccount(cardEntity.getAlipayAccount());
                break;
            case "10014002"://微信
                entity.setCashCardAccount(cardEntity.getWxAccount());
                break;
            case "10014003"://银行卡
                entity.setCashCardAccount(cardEntity.getBankcardNum());
                break;
            default:
                throw new RuntimeException("未知卡类型");
        }
        //服务费，收费金额乘以服务费收取比例
        entity.setDisparityAmount(entity.getAmount().multiply(chargeRate));
        //实际到账金额，提现金额减去服务费
        entity.setSettleAmount(entity.getAmount().subtract(entity.getDisparityAmount()));
        entity.setCashOrderStatusType("10015001");//待处理
        entity.setCreateTime(new Date());
        itUserCashOrderService.insert(entity);
        //账户变更
        itUserAccountService.alterBrokerageAmount("10000002", "10001008", TLMap.getUserId(), entity.getCashOrderId(), entity.getAmount());
    }

    @Override
    public Page<TUserCashOrderEntity> listCashOrder(QueryUserCashOrderEntity entity) {
        Wrapper<TUserCashOrderEntity> wrapper = new EntityWrapper<TUserCashOrderEntity>()
                .where("1=1")
                .eq(StringUtils.isNotBlank(entity.getUserId()), "user_id", entity.getUserId())
                .eq(StringUtils.isNotBlank(entity.getAccountChangeBusinessType()), "account_change_business_type", entity.getAccountChangeBusinessType())
                .eq(StringUtils.isNotBlank(entity.getAccountTrend()), "account_trend", entity.getAccountTrend())
                .orderBy("create_time desc");
        Page<TUserCashOrderEntity> page = itUserCashOrderService.selectPage(new Query<TUserCashOrderEntity>(BeanMapUtil.toPageQuery(entity)).getPage(), wrapper);
        return page;
    }

    @Override
    public TUserCashOrderEntity getCashOrder(String orderId) {
        return itUserCashOrderService.selectById(orderId);
    }

    /**
     * 必传参数校验
     *
     * @param entity
     */
    private void validateParam(TUserCashOrderEntity entity) {
        if (StringUtils.isBlank(entity.getUserCardId())
                || null == entity.getAmount()) {
            throw new RuntimeException("必传参数为空");
        }
        TUserCardEntity cardEntity = itUserCardService.selectById(entity.getUserCardId());
        if (null == cardEntity) {
            throw new RuntimeException("目标卡不存在");
        }
    }
}
